const {deleteFile} = require("../helper/file");
const {generateFileContent} = require("../template/function");
const {travelAndReadFile} = require("../helper/file");
const {writeFile} = require("../helper/file");
const KoaRouter = require('koa-router')
const path = require('path');
const {getESMFunction} = require("../template/export");
const router = new KoaRouter()

// 遍历本地的函数文件并返回内容
router.get(`/getFunctions`,   async(ctx) => {
    const p = path.resolve('./functions')
    const res = await travelAndReadFile(p)
    ctx.body = res
})
// 修改本地的函数文件内容
router.post(`/updateFunctions`,   async(ctx) => {
    const {key,name,remark,code,doc} = ctx.request.body
    const p = path.resolve('./functions/'+key + '.js')
    const content = generateFileContent({key,name,remark,code,doc})
    const res = await writeFile(p,content)
    ctx.body = res
})
// 删除本地的函数文件
router.post(`/deleteFunctions`,   async(ctx) => {
    const {key} = ctx.request.body
    const p = path.resolve('./functions/'+key + '.js')
    const res = await deleteFile(p)
    ctx.body = res
})
// 导出ESM函数文件到本地
router.post(`/exportFunctions`,   async(ctx) => {
    const {codes,name} = ctx.request.body
    const p = path.resolve('./exports/'+name+'.js')
    if(!codes){
        ctx.body = 'no function'
        return
    }
    const content = codes.split('//**//').map(item=>getESMFunction(item)).join('')
    const res = await writeFile(p,content)
    res.content = content
    ctx.body = res
})
module.exports = router
